import 'package:chat/common/service/HttpService.dart';
import 'package:chat/common/utils/storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import '../../../../common/model/User.dart';

class AddfriendController extends GetxController {
  AddfriendController();

  final TextEditingController searchUserNameController = TextEditingController();

  var searchUserList = <UserModel>[].obs;
  RxString hasSearch = "请输入用户名搜索好友".obs;

  _initData() {
    update(["addfriend"]);
  }

  @override
  void onInit() {
    super.onInit();
  }

  Future<void> fetchData() async {
    try {
      String searchContent = searchUserNameController.text.trim();
      if (searchContent.isEmpty) {
        searchUserList.clear();
        hasSearch.value = "请输入用户名搜索好友";
        return;
      }

      if(searchContent.length<3){
        searchUserList.clear();
        hasSearch.value = "搜索的用户账号长度不足3位";
        return;
      }

      UserModel? user = await Storage().getUser();
      final response = await HttpService.to.get("/friend/search", query: {"userId": user?.uid, "username": searchContent});

      if (response.statusCode == 200 && response.data["code"] == 200) {
        final List<dynamic> list = response.data["data"] ?? [];
        searchUserList.value = list.map((e) => UserModel.fromJson(e)).toList();
      } else {
        hasSearch.value = "未找到匹配的用户";
        searchUserList.clear();
      }
    } catch (e) {
      print("搜索好友错误: $e");
    }
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  @override
  void onClose() {
    super.onClose();
    searchUserNameController.dispose();
  }
}
